<?php


class Rating extends A_Content {
	
	public function add() {
		$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."rating(add_date) VALUES(NOW());");
		$id = $this->_top->_sql->last_insert_id();
		return $this->getById($id);
	}


	public function getById($id) {
		if (!isset($this->_cashe_obj[$id])) {
			$this->_cashe_obj[$id] = new SingleRating($this->_top,$this,$id);
		}
		
		return $this->_cashe_obj[$id];
	}
}



class SingleRating extends A_SingleContent {
	
	protected function loader() {
		$get_data = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."rating WHERE rating_id={$this->_content_id}");
		if (count($get_data)==0) {
			throw $this->_top->Utils->PushError('Rating object not found Id: '.$this->_content_id,'Системная ошибка. Обратитесь к администратору');
		} else {
			$this->_data = $get_data[0];
		}
	}

	//добавляем новый рейтинг к товару
	public function voite($aScore){
        //пересчитываем новый бал
        $score = $this->score;
        $voites = $this->voites;
        $this->score = ($score*$voites + $aScore )/($voites + 1);
        //увеличиваем кол-во голосований
        $this->voites = $this->voites + 1;        
	}	
	
	//"голосует" админ
	public function adminVoite($aNewScore, $aNewVoites){
	   $this->score = $aNewScore;
	   $this->voites = $this->voites + $aNewVoites;
	}

	//запомним юзера, который добавил рейтинг
	public function toHistory($aScore, $aUser_id){
		$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."rating_history(rating_id, score, user_id) VALUES($this->_content_id, $aScore, $aUser_id)");        
	}

	//вытянуть кол-во баллов по конкретному пользователю
	public function fromHistory($aUser_id){
        $get_data = $this->_top->_sql->exe("SELECT score FROM ".TAB_PREF."rating_history WHERE rating_id={$this->_content_id} AND user_id=$aUser_id");
        if( count($get_data) )
            return $get_data[0]['score'];
        else
            return 0;
	}
	
	public function __get($param) {
        return $this->_data[$param];
	}
	
	
	public function __set($param, $value) {
        $value = $this->_top->Utils->prepareValueForSQL($value);
			
        $this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."rating SET $param='$value' WHERE rating_id={$this->_content_id}");
        $this->_data[$param] = $value;
        return true;	
	}
	
	//удаляем одиночный бал
	protected function deleter() {
	
	}
	
	
}